package com.neusoft.nep.GridOfficer.controller;


import com.neusoft.nep.common.FileUtils;
import com.neusoft.nep.entity.Feedback;
import com.neusoft.nep.entity.GirdFeedback;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class GirdOfficerFeedBackInfoViewController {
    @FXML
    private Label labUser;         // 反馈用户
    @FXML
    private Label labGrid;         // 网格
    @FXML
    private Label labAddress;      // 详细地址
    @FXML
    private Label labLevel;        // 预估AQI等级
    @FXML
    private Label labInfo;         // 信息描述
    @FXML
    private Label labLevel1;       // SO2浓度对应等级
    @FXML
    private Label labLevel2;       // CO浓度对应等级
    @FXML
    private Label labLevel3;       // PM2.5浓度对应等级
    @FXML
    private TextField txt_SO2;     // SO2浓度输入
    @FXML
    private TextField txt_CO;      // CO浓度输入
    @FXML
    private TextField txt_PM;      // PM2.5浓度输入
    @FXML
    private Label labFinalLevel;   // 最终AQI等级显示
    @FXML
    private Button btn_submit;     //提交实时检测数据按钮
    @FXML
    private Button btn_ret;        //返回List的按钮

    private Feedback receivedData; //获取由GirdOfficerBackListViewController传来的监测信息的对象
    private Pattern numberPattern = Pattern.compile("^\\d+(\\.\\d+)?$"); // 数字格式验证
    private String SO2;            //SO2等级
    private String CO;             //CO等级
    private String PM;             //PM2.5等级
    private String finalLevel;     //实测AQI等级
    private String finalLevelInfo; //实测AQI等级描述

    @FXML
    public void initialize() {
        // 为文本框添加实时监听
        txt_SO2.textProperty().addListener((o, oldVal, newVal) -> updateAllLevels());
        txt_CO.textProperty().addListener((o, oldVal, newVal) -> updateAllLevels());
        txt_PM.textProperty().addListener((o, oldVal, newVal) -> updateAllLevels());

        // 初始化显示
        updateAllLevels();
    }

    //点击返回的时候，需要调用UserManagerViewController中的dialog对象的close方法
    public void ret() throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("/com/neusoft/nep/GridOfficer/view/GridOfficerFeedBackListView.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = btn_ret.getScene();
        scene.setRoot(root);
        Stage stage = (Stage) scene.getWindow();
        stage.show();
    }

    //获取由GirdOfficerBackListViewController传来的监测信息的
    public void setData(Feedback receivedData) {
        this.receivedData = receivedData;
        dataUpdate();
    }

    //用于更新实时检测界面的初始检测信息
    public void dataUpdate() {
        labUser.setText(receivedData.getName());
        labGrid.setText(receivedData.getProvince() + receivedData.getCity());
        labAddress.setText(receivedData.getAddress());
        labLevel.setText(receivedData.getAqiLevel());
        labInfo.setText(receivedData.getDescription());
    }

    // 获取污染物对应的AQI等级
    private int getAqiLevel(double concentration, String pollutantType) {
        if ("SO2".equals(pollutantType)) {
            return getLevelByRange(concentration, 50, 150, 475, 800, 1600);
        } else if ("CO".equals(pollutantType)) {
            return getLevelByRange(concentration, 5, 10, 35, 60, 90);
        } else if ("PM2.5".equals(pollutantType)) {
            return getLevelByRange(concentration, 35, 75, 115, 150, 250);
        }
        return -1; // 异常情况
    }

    // 通用等级计算方法
    private int getLevelByRange(double concentration, double r1, double r2, double r3, double r4, double r5) {
        if (concentration >= 0 && concentration <= r1) return 1;
        else if (concentration > r1 && concentration <= r2) return 2;
        else if (concentration > r2 && concentration <= r3) return 3;
        else if (concentration > r3 && concentration <= r4) return 4;
        else if (concentration > r4 && concentration <= r5) return 5;
        else if (concentration > r5) return 6;
        return -1;
    }

    // 获取等级对应的信息（颜色和说明）
    private Map<String, Object> getAqiInfo(int level) {
        Map<String, Object> infoMap = new HashMap<>();
        switch (level) {
            case 1:
                infoMap.put("color", "#02E300"); // 绿色
                infoMap.put("desc", "优");
                infoMap.put("levelName", "一级");
                break;
            case 2:
                infoMap.put("color", "#FFFF00"); // 黄色
                infoMap.put("desc", "良");
                infoMap.put("levelName", "二级");
                break;
            case 3:
                infoMap.put("color", "#FF7E00"); // 橙色
                infoMap.put("desc", "轻度污染");
                infoMap.put("levelName", "三级");
                break;
            case 4:
                infoMap.put("color", "#FE0000"); // 红色
                infoMap.put("desc", "中度污染");
                infoMap.put("levelName", "四级");
                break;
            case 5:
                infoMap.put("color", "#98004B"); // 紫色
                infoMap.put("desc", "重度污染");
                infoMap.put("levelName", "五级");
                break;
            case 6:
                infoMap.put("color", "#7E0123"); // 褐红色
                infoMap.put("desc", "严重污染");
                infoMap.put("levelName", "六级");
                break;
            default:
                infoMap.put("color", "#CCCCCC"); // 灰色
                infoMap.put("desc", "未知等级");
                infoMap.put("levelName", "未知");
        }
        return infoMap;
    }

    //将int型的四个数据全部改为String
    private void updateLevel() {

    }

    // 统一更新所有等级标签
    private void updateAllLevels() {
        double so2 = getValidConcentration(txt_SO2.getText());
        double co = getValidConcentration(txt_CO.getText());
        double pm25 = getValidConcentration(txt_PM.getText());

        int so2Level = getAqiLevel(so2, "SO2");
        int coLevel = getAqiLevel(co, "CO");
        int pm25Level = getAqiLevel(pm25, "PM2.5");

        // 更新各污染物等级标签
        updateLevelLabel(labLevel1, so2Level);
        updateLevelLabel(labLevel2, coLevel);
        updateLevelLabel(labLevel3, pm25Level);

        // 计算最终等级
        int finalLevel = Math.max(Math.max(so2Level, coLevel), pm25Level);
        updateFinalLevelLabel(finalLevel);
        //判断SO2最终AQI等级
        switch (so2Level) {
            case 1:
                SO2 = "一";
                break;
            case 2:
                SO2 = "二";
                break;
            case 3:
                SO2 = "三";
                break;
            case 4:
                SO2 = "四";
                break;
            case 5:
                SO2 = "五";
            case 6:
                SO2 = "六";
                break;
            default:
                SO2 = "未知";
                break;
        }//判断CO最终AQI等级
        switch (coLevel) {
            case 1:
                CO = "一";
                break;
            case 2:
                CO = "二";
                break;
            case 3:
                CO = "三";
                break;
            case 4:
                CO = "四";
                break;
            case 5:
                CO = "五";
            case 6:
                CO = "六";
                break;
            default:
                CO = "未知";
                break;
        }//判断PM2.5最终AQI等级
        switch (pm25Level) {
            case 1:
                PM = "一";
                break;
            case 2:
                PM = "二";
                break;
            case 3:
                PM = "三";
                break;
            case 4:
                PM = "四";
                break;
            case 5:
                PM = "五";
            case 6:
                PM = "六";
                break;
            default:
                PM = "未知";
                break;
        }

    }

    // 更新单个污染物等级标签
    // 更新单个污染物等级标签（优化显示完整等级名称）
    private void updateLevelLabel(Label label, int level) {
        Map<String, Object> info = getAqiInfo(level);
        String levelName = (String) info.get("levelName");

        // 直接显示完整等级名称（如一、二...）
        label.setText(levelName != null ? levelName : "未知");

        label.setStyle("-fx-background-color: " + info.get("color") + ";" +
                "-fx-text-fill:" + getReadableTextColor((String) info.get("color")) + ";" +
                "-fx-border-color: black;" +
                "-fx-alignment: center;" +
                "-fx-font-weight: bold;");
    }

    // 更新最终等级标签
    private void updateFinalLevelLabel(int level) {
        Map<String, Object> info = getAqiInfo(level);
        String displayText = "实测AQI等级：" + info.get("levelName") + " " + info.get("desc");
        //获得最后AQI等级和等级描述
        finalLevel = info.get("levelName").toString();
        finalLevelInfo = info.get("desc").toString();
        labFinalLevel.setText(displayText);
        labFinalLevel.setStyle("-fx-background-color: " + info.get("color") + ";" +
                "-fx-text-fill: " + getReadableTextColor((String) info.get("color")) + ";" +
                "-fx-border-color: black;" +
                "-fx-alignment: center;" +
                "-fx-font-size: 16px;" +
                "-fx-font-weight: bold;");
    }

    // 获取与背景色对比明显的文本颜色
    private String getReadableTextColor(String hexColor) {
        // 简化版：计算亮度，亮度低时用白色，否则用黑色
        int r = Integer.parseInt(hexColor.substring(1, 3), 16);
        int g = Integer.parseInt(hexColor.substring(3, 5), 16);
        int b = Integer.parseInt(hexColor.substring(5, 7), 16);
        double brightness = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
        return brightness > 0.5 ? "black" : "white";
    }

    // 获取有效浓度值
    private double getValidConcentration(String text) {
        if (text == null || text.trim().isEmpty()) return -1;
        if (numberPattern.matcher(text).matches()) {
            return Double.parseDouble(text.trim());
        }
        return -1;
    }

    // 获取等级文本
    private String getLevelText(int level) {
        Map<String, Object> info = getAqiInfo(level);
        return (String) info.get("levelName") + " " + info.get("desc");
    }

    //获取系统时间
    public String getSystemTime() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return now.format(formatter);
    }

    //将网格员实测的数据写入传输给系统管理员的文件
    public void addFile() throws IOException {
        GirdFeedback gird1 = new GirdFeedback(receivedData.getIndex(), receivedData.getName(), receivedData.getSex(), receivedData.getPhoneNumber(), receivedData.getBirthday(), receivedData.getProvince(), receivedData.getCity(), receivedData.getAddress(), receivedData.getAqiLevel(), receivedData.getDescription(), getSystemTime(), SO2, CO, PM, finalLevel, finalLevelInfo);
        String fileName = GirdOfficerLoginViewController.getOfficerName();
        //根据当前登录网格员姓名写入对应文件
        Map<String, GirdFeedback> girdFeedbackMap = new HashMap<>();
        FileUtils.readMapObject("gird" + fileName + "back.txt");
        girdFeedbackMap.put(String.valueOf(gird1.getIndex()), gird1);
        FileUtils.writeMapObject("gird" + fileName + "back.txt", girdFeedbackMap);
        System.out.println("successful");

        //获得准备删除的GirdOfficerFeedBackListViewController类中的那条数据的key（index）
        GirdOfficerFeedBackListViewController.delInfo(GirdOfficerFeedBackListViewController.getIndex());
        //返回List
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("/com/neusoft/nep/GridOfficer/view/GridOfficerFeedBackListView.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = btn_submit.getScene();
        scene.setRoot(root);
        Stage stage = (Stage) scene.getWindow();
        stage.show();

    }


}
